<?php

/* 
 * 社区的相关函数
 */

namespace app\web\controller;

use app\common\Base;

class Community extends Base {
    
    //话题列表的页面函数
    public function topicset(){
        
        $m= model('Topic');
        $condition=array();
        $pid= input('pid',0,'intval');
        if($pid!=0){
            $condition['type']=$pid;
        }
        $list=$m->where($condition)->limit(0,config('community.mosthot'))->order('support DESC')->select();
        $mosthot=array();
        //$lists=$list->toArray();
        //dump($lists); return;
        foreach ($list as $key=>$row){
           // dump($row);
           // $mosthot[$key]=array_merge($row->toArray(),$row->topiclist->toArray());
            $mosthot[$key]['title']=$row['title'];
            $mosthot[$key]['topic_id']=$row['topic_id'];
            $mosthot[$key]['user_id']=$row['user_id'];
            $mosthot[$key]['in_time']=$row['in_time'];
            $mosthot[$key]['support']=$row['support'];
            $mosthot[$key]['type']=$row['type'];
            $mosthot[$key]['head']=$row->topiclist ? $row->topiclist->head : 'default.png';
            //$mosthot[key].
            // dump($row->topiclist);
        }
      //  return;
        $this->assign('nownav',1);
        $this->assign('mosthot',$mosthot);
        $this->assign('pid',$pid);
        return $this->fetch('community/topicset');
    }
    
    //获取话题列表的 api 配合 layui的flow 流加载
    public function gettopiclist(){
        $page= intval(input('page',1,'intval'));
        $m= model('Topic');
        $list=$m->where(1)->limit(($page-1)* config('community.pagenum'),config('community.pagenum'))->order('in_time DESC')->select();
        $ret=[];
        foreach ($list as $key=>$row){
            if(!empty($row)){
                $ret[$key]=array_merge($row->toArray(),$row->topiclist?$row->topiclist->toArray():[]);
            }
        }
        $count=db('topic')->count();
        $res['pages'] = ceil($count / config('community.pagenum'));
        $this->assign('list',$ret);
        $res['html']= $this->fetch();
        return json($res);
    }
    
    //获取用户的头像的函数,返回头像的路径
    //相会于 /upload/users/head/******
    private function get_user_head($userid){
        $res=db('users')->find($userid);
        return $res['head'];
    }

    //显示文章内容的相关页面
    public function articles() {
        $topic_id = input('tid', 0, 'intval');
        $is_your= $this->is_your_topic($topic_id, $this->user_id);
        
        $article = db('topic')->find($topic_id);
        if(empty($article)){
            $this->error_ui('该文章不在地球上了');  
        }
        if ($is_your || $this->have_power(9)||$article['status']==1) {
            $article['head'] = $this->get_user_head($article['user_id']);
            $this->assign('article', $article);
            $this->assign('is_yours', $this->user_id == $article['user_id'] ? true : false);
            $this->assign('is_admin', $this->have_power(9));
            return $this->fetch();
        } 
        else {
            $this->error_ui('该文章未发布,或被隐藏了');
        }
        
    }
    
    
    // 获取用户的OJ币 数量
    private function get_coin_num($userid){
        $res=db('users')->find($userid);
        return intval($res['ojcoin']);
    }

    // 使得某个用户 OJ币 减一
    private function reduce_coin($userid){
        $condition['user_id']=$userid;
        db('users')->where($condition)->setDec('ojcoin');
    }
    
    //被点赞的topic 支持数 加一
    private function do_support($tid){
        $condition['topic_id']=$tid;
        return db('topic')->where($condition)->setInc('support');
    }
    
    //根据 tipic_id 获取用户
    private function get_topic_user($tid){
        $res=db('topic')->find($tid);
        return $res['user_id'];
    }
    
    //往message插入消息,对用户进行提醒 [有人赞了你的文章]
    private function send_support_message($from,$to,$tid){
        if($from==$to) return ;
        $data['user_id']=$to;
        $data['status']=1;
        
        $info = db('topic')->find($tid);
        if(empty($info))
            return;
        $this->assign('from', $from);
        $this->assign('title', htmlspecialchars($info['title']));
        $this->assign('tid',$tid);
        $data['content']=$this->fetch("send_support_message");
        $data['time']=time();
        db('message')->insert($data);
    }
    
    //对于文章的点赞 api 函数
    public function support() {
        $tid=input('tid',0,'intval');
        $res = array();
        if (!$this->is_login) {
            $res['code'] = 2;
            $res['msg'] = '未登录';
        } else {
            $coin = $this->get_coin_num($this->user_id);
            if ($coin > 0) {
                $this->reduce_coin($this->user_id);
                $rrr=$this->do_support($tid);
                if($rrr==FALSE){
                    $res['code'] = 4;
                    $res['msg'] = '其他错误';
                }
                else {
                    $this->send_support_message($this->user_id, $this->get_topic_user($tid),$tid);
                    $res['code'] = 0;
                    $res['msg'] = '谢谢您的支持,OJ币 -1';
                }
            } else {
                $res['code'] = 3;
                $res['msg'] = 'OJ币不足';
            }
        }
        return json($res);
    }
    
    // 获取用户 ac 的题目数量
    private function get_ac_num(){
        $res=db('users')->find($this->user_id);
        return $res?$res['solved']:0;
    }
    
    //发表话题(文章)
    public function addtopic(){
        if(!$this->is_login){
            $this->error_ui('请先登录');
            return ;
        }
        $ac_num= $this->get_ac_num();
        if($ac_num< config('community.ac_problem_limit')){
            $this->error_ui('请保证ac题目数量大于'.config('community.ac_problem_limit'));
            return;
        }
        $this->assign('pid',input('pid',null,'intval'));
        return $this->fetch();
    }
    public function do_addtopic(){        
        if(!$this->is_login){
            $this->error_ui('请先登录');
            return ;
        }
        $ac_num= $this->get_ac_num();
        if($ac_num< config('community.ac_problem_limit')){
            $this->error_ui('请保证ac题目数量大于'.config('community.ac_problem_limit'));
            return;
        }
        $data['title']= $this->remove_xss(input('title',"","trim"));
        $data['type']=input('pid',0,'intval');
        $data['content']= $this->remove_xss(input('content',""));
        $topic_id=input('tid',null,'intval');
        //dump($data);return ;
        if($data['title']==""||$data['content']==""){
            $this->error_ui('标题或者文章为空,不可以哦');
        }
        if ($topic_id == null) { //添加
            $data['in_time']=time();
            $data['status']=1;
            $data['support']=0;
            $data['user_id']= $this->user_id;
            $data['ip']= request()->ip();
            $res = db('topic')->insert($data);
            if ($res == 1) {
                $topic_id = db('topic')->getLastInsID();
                $this->success_ui('发布成功', url('web/Community/articles', 'tid=' . $topic_id));
            } else {
                $this->error('error ,please send email to administrator admin email:' . config('admin_email'));
                return;
            }
        }
        else { //编辑
            $tinfo=$this->get_topic_info($topic_id);
            if($tinfo==FALSE){
                $this->error_ui('文章早已经不见鸟~');
            }
            if ($tinfo['user_id'] == $this->user_id) {
                db('topic')->where(['topic_id' => $topic_id])->update($data);
                $this->success_ui('发布成功', url('web/Community/articles', 'tid=' . $topic_id));
            } else {
                $this->error_ui('只能编辑自己的文章哦~');
            }
        }
    }
    

    public function get_newest_topic(){
        $res=db('topic')->limit(0, config('community.mosthot'))->order('in_time DESC')->select();
        $this->assign('list',$res);
        return $this->fetch();
    }
    public function getproblemtopiclist(){
        $page= intval(input('page',1,'intval'));
        $pid=input('pid',0,'intval');
//        dump($pid);
//        dump($page);
//        return ;
        $m= model('Topic');
        $condition['type']=$pid;
        $list=$m->where($condition)->limit(($page-1)* config('community.pagenum'),config('community.pagenum'))->order('in_time DESC')->select();
        $ret=[];
        foreach ($list as $key=>$row){
            $ret[$key]=array_merge($row->toArray(),$row->topiclist->toArray());
        }
        $count=db('topic')->where($condition)->count();
        $res['pages'] = ceil($count / config('community.pagenum'));
        $this->assign('list',$ret);
        $res['html']= $this->fetch('gettopiclist');
        return json($res);
    }
    
    private function get_sign_time(){
        $res=db('users')->find($this->user_id);
        return $res?$res['sign_time']:0;
    }
    
    private function do_sign_in(){
        db('users')->where('user_id', $this->user_id)->update(['sign_time'=> time()]);
        db('users')->where('user_id', $this->user_id)->setInc('ojcoin');
    }

    //用户的签到
    public function user_sign(){
        $ret['code']=0;
        if(!$this->is_login){
            $ret['code']=1;
            $ret['msg']='未登录';
            return json($ret);
        }
        $last_time= $this->get_sign_time();
        
        if(time()-$last_time>= config('community.sign_time')){
            $this->do_sign_in();
            $ret['code']=0;
            $ret['msg']='签到成功,OJ币+1';
        }
        else{
            $ret['code']=1;
            $ret['msg']='签到失败,已经签到过了哦';
        }
        return json($ret);
    }
    
    
    // 获取上次的签到时间
    public function get_last_sing_time(){
        if(!$this->is_login){
            echo '未登录';
            return ;
        }
        $res=db('users')->find($this->user_id);
        $out='未登录';
        if(!empty($res)){
            $out= date('m-d H:i:s', $res['sign_time']);
        }
        return $out;
    }
    
    //
    public function editor_post(){
        $tid= input('tid',null,'intval');
        if($tid==null) {
            $this->error_ui('没有要编辑的文章吗?');
        }
        if(!$this->is_login){
            $this->error_ui('请先登录!');
        }
        $article= db('topic')->find($tid);
        
        $this->assign('article',$article);
        return $this->fetch();
    }
    private function get_topic_info($topic_id){
        $res=db('topic')->find($topic_id);
        if(empty($res)){
            return false;
        }
        else {
            return $res;
        }
    }

    private function is_your_topic($tid,$uid){
        $info= $this->get_topic_info($tid);
        if($info!=FALSE&&$info['user_id']==$uid){
            return true;
        }
        else {
            return false;
        }
    }
    
    public function do_set_topic() { // topic 的一些设置
        $tid = input('tid', null, 'intval');
        $type = input('type', null, 'intval');
        if ($tid == NULL || $type == NULL) {
            $ret['code'] = 1;
            $ret['msg'] = '没有该文章哟~';
            return json($ret);
        }
        if (!$this->is_login) {
            $ret['code'] = 1;
            $ret['msg'] = '请先登录哟~';
            return json($ret);
        }
        $topic_info= $this->get_topic_info($tid);
        if($topic_info==FALSE){
            $ret['code'] = 1;
            $ret['msg'] = '该文章早已经不见鸟~';
            return json($ret);
        }
        if ($this->have_power(9) || $topic_info['user_id']== $this->user_id) {//如果是 管理员或者自己的
            if ($type == 0) {
                if ($this->have_power(10) || $topic_info['user_id'] == $this->user_id) {
                    db('reply')->where(['topic_id' => $tid])->delete();
                    $res = db('topic')->delete($tid);
                    $ret['code'] = 0;
                    $ret['msg'] = '删除成功';
                    if ($topic_info['user_id'] != $this->user_id) {
                        $this->sendmessage($topic_info['user_id'], "管理员 删除了你的文章");
                    }
                    $ret['url'] = url('web/Community/topicset');
                    return json($ret);
                } else {
                    $ret['msg'] = '没有权限';
                    $ret['code'] = 1;
                    return json($ret);
                }
            } 
            else if ($type == 1) {
                $res = db('topic')->where('topic_id', $tid)->setField('status', 0);
                $ret['code'] = 0;
                if($topic_info['user_id'] != $this->user_id){
                    $this->sendmessage($topic_info['user_id'], "管理员 隐藏了<a href='"
                            .url('web/Community/articles',['tid'=>$topic_info['topic_id']]). "'>"
                            . "<cite>你的文章</cite></a>");
                }
                $ret['msg'] = '隐藏成功';
                return json($ret);
            } else {
                $res = db('topic')->where('topic_id', $tid)->setField('status', 1);
                $ret['code'] = 0;
                $ret['msg'] = '显示成功';
                return json($ret);
            }
        } else {
            $ret['code'] = 1;
            $ret['msg'] = '你没有权限~';
            return json($ret);
        }
    }
    public function sendmsg() {
        if($this->is_login==FALSE){
            $this->error_ui('清先登陆');
        }
        $uid= input('user_id',null);
        $this->assign('user_id',$uid);
        return $this->fetch();
    }
    public function do_sendmsg(){
        if($this->is_login==FALSE){
            $this->error_ui('清先登陆');
        }
        $senduid= input('userid');
//        dump($senduid);
//        return ;
        $content="用户<a href='". url('web/Account/info',['user_id'=> $this->user_id])."'><cite>".
                $this->user_id."</cite></a>说：<br />" .htmlspecialchars(input('content')).
                "<br /><br /><div class='news-content-author'><a href='". url('web/Community/sendmsg',['user_id'=> $this->user_id])."'><cite>回复他</cite></a></div><br />";
        $this->sendmessage($senduid,$content);
        $this->success_ui('发送成功', url('web/message/messageset'));
    }
}
